package com.jwb.pub.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jwb.pub.dao.BaseDAO;
import com.jwb.pub.model.JavaModel;
import com.jwb.pub.service.PrivilegeService;

/**
 * 
 * @description:权限管理接口实现
 * @author liuyn
 * 
 * @createDate 2018-03-15
 * @createTime 上午10:48:37
 */
@Service
public class PrivilegeServiceImpl implements PrivilegeService
{
	@Autowired
	private BaseDAO baseDAO;
	
	/**
	 * 
	 * @description：业务功能组列表转JSON
	 * @author liuyn
	 * @param privGroups
	 * 
	 * @return
	 * 
	 * @createDate 2018-03-15
	 * @createTime 下午3:29:48
	 */
	public JSONObject getPGroupsJson(JSONObject jsdata)
	{
		JSONObject jsobject = new JSONObject();
		String sqlWhere="";
		
		String sql = "";
		try {
				sql = 	" select distinct priv_group privGroup, group_order groupOrder"+
			            " from privilege"+
			            " where 1 = 1 "+sqlWhere+
			            "order by group_order";
				jsobject = baseDAO.findBySqlToJosn(sql, "privlist");

		} catch (Exception e) {

			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "获取数据失败");

		}
		return jsobject;	
		
	}
	
	
	/**
	 * 
	 * @description：显示权限列表
	 * @author liuyn	 * 
	 * @return
	 * @throws DBException	 * 
	 * @createDate 2018-3-7
	 * @createTime 下午5:05:35
	 */
	public JSONObject getPrivListJson(JSONObject jsdata)
	{
		JSONObject jsobject = new JSONObject();
		String sql = "";
		String sqlWhere="";
		if(jsdata.containsKey("groupOrder")){
			sqlWhere=" and group_order='"+jsdata.getString("groupOrder")+"'";
		}
		try {
				sql = 	"select priv_name privname,"+
						"       remarks remarks,"+
						"       priv_group privgroup,"+
						"       sys_name sysName,"+
						"       display_order displayorder,"+
						"       group_order grouporder,"+
						"       priv_code privcode,"+
						"       action_name actionname,"+
						"       pri_type pritype,"+
						"       open_sts opensts,"+
						"		case open_sts when '0' then '已禁用' when '1' then '已启用' else '' end openstsdesc,"+
						"		'' sprivcode"+
						"  from v_privilege"+						
			            " where 1 = 1 "+sqlWhere+
			            "order by group_order";
			jsobject = baseDAO.findBySqlToJosn(sql, "privlist");

		} catch (Exception e) {

			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "获取数据失败");

		}
		return jsobject;	
		
	}
	
	
	
	/*
	 * @description：保存功能开关状态
	 * @author liuchang	 * 
	 * @return
	 * @throws DBException	 * 
	 * @createDate 2018-3-7
	 * @createTime 下午14:57:35
	 */
	
	public JSONObject privilegeStsSave(JSONObject jsdata){
		JSONObject jsobject = new JSONObject();
		
		try{
			String opensts=jsdata.getString("openSts");
			String privCode=jsdata.getString("privCode");
			if(opensts.equals("0")) opensts="1";
			else opensts="0";
			
			String sql= "Update privilege SET open_sts = ? Where priv_code = ? ";
			ArrayList<JavaModel> list = new ArrayList<>();
			list.add(new JavaModel(opensts));
			list.add(new JavaModel(privCode));
			if (baseDAO.excuteSql(sql, list)) {
				jsobject.put("openSts", opensts);
				if (opensts.equals("0"))
					jsobject.put("respmsg", "权限开启成功");
				else
					jsobject.put("respmsg", "权限关闭成功");
				jsobject.put("respCode", "0");
			} else {
				jsobject.put("respCode", "1");
				jsobject.put("respmsg", "权限更改失败!");
			}
		}catch(Exception e){
			e.printStackTrace();
			jsobject.put("respCode", "1");
			jsobject.put("respmsg", "权限更改失败!");
			return jsobject;
		}
		
		return jsobject;
	}
	
	/**
	 * 
	 * @description：获取单条权限JSON
	 * @author ZhengYu
	 * 
	 * @param privilege
	 * @return
	 * 
	 * @createDate 2014-12-19
	 * @createTime 下午2:51:33
	 */
	public JSONObject getPrivJson(JSONObject jsdata){
		JSONObject jsobject = new JSONObject();
		
		
		try{
			String privCode=jsdata.getString("privCode");
			String sql = "SELECT priv_code privcode, priv_name privname, remarks, priv_group privgroup,"
					+ " sys_name sysname, display_order displayorder, group_order grouporder, "
					+ " action_name actionname, pri_type pritype, open_sts opensts, '' sprivcode "
					+ " From privilege "
					+ " Where priv_code = '"+privCode+"'";
			jsobject = baseDAO.findBySqlToJosn(sql);
			
			
		}catch(Exception e){
			jsobject.put("respCode", "9");
			jsobject.put("respmsg", "系统忙，请联系系统管理员");
		}
		
		return jsobject;
	}
	
	/**
	 * 
	 * @description：添加权限时获取所属组信息
	 * @author LIU CHANG
	 * 
	 * @param privGroup
	 * @return
	 * @throws DBException
	 * 
	 * @createDate 2014-3-7
	 * @createTime 下午5:13:29
	 */
	public JSONObject getPrivilegeGroupInfo(JSONObject jsdata){
		JSONObject jsobject = new JSONObject();
		try {
			String groupOrder = jsdata.getString("groupOrder");
			String sql =" select distinct priv_group privgroup, sys_name sysname, group_order grouporder " +
					" FROM privilege " +
					" where group_order = '"+groupOrder+"'";
			jsobject=	baseDAO.findBySqlToJosn(sql, "pglist");
		} catch (Exception e) {
			jsobject.put("respCode", "9");
			e.printStackTrace();
			return jsobject;
		}
		
		
		return jsobject;
	}
	
	
	/**
	 * 
	 * @description：保存权限
	 * @author LIUCHANG
	 * 
	 * @param privilege
	 * @throws DBException
	 * 
	 * @createDate 2018-3-16
	 * @createTime 下午5:15:25
	 */
	
	public JSONObject privilegeSave(JSONObject jsdata){
		JSONObject jsobject = new JSONObject();
		String cntSql="";

		try {
	    	String privCode = jsdata.getString("privCode");
	    	String privName = jsdata.getString("privName");
	    	String remarks = jsdata.getString("remarks");
	    	String groupOrder = jsdata.getString("groupOrder");
	    	String privGroup = jsdata.getString("privGroup");
			if(privCode==null||privCode.trim().equals("")){
				cntSql="SELECT count(*) FROM privilege where priv_name='"+privName+"' OR remarks='"+remarks+"' ";
			}else{
				cntSql="SELECT count(*) FROM privilege where (priv_name='"+privName+"' OR remarks='"+remarks+ "') AND priv_code <>'"+privCode+"'";
			}
			int cnt = baseDAO.findBySqlCnt(cntSql);
			if(cnt>0){
				jsobject.put("respCode", "2");
				jsobject.put("respmsg", "权限已存在，请修改!");
			}else{
				//groupOrder
				int dorder = getSaveGroupOrder(groupOrder);
				if(dorder !=-1){
					dorder = dorder + 1;
					String disorder = String.valueOf(dorder);
					if(privCode==null||privCode.trim().equals("")){
						String addSql="INSERT INTO privilege (priv_name,remarks,group_order,priv_group,pri_type,open_sts,display_order) "
								+" VALUES(?,?,?,?,'S','1',?)";
						ArrayList<JavaModel> list = new ArrayList<>();
						list.add(new JavaModel(privName));
						list.add(new JavaModel(remarks));
						list.add(new JavaModel(groupOrder));
						list.add(new JavaModel(privGroup));
						list.add(new JavaModel(disorder));
						baseDAO.excuteSql(addSql, list);						
						
					}else{
						String updateSql="Update privilege SET priv_name=?, remarks=? WHERE priv_code=?";
						ArrayList<JavaModel> list = new ArrayList<>();
						list.add(new JavaModel(privName));
						list.add(new JavaModel(remarks));
						list.add(new JavaModel(privCode));
						baseDAO.excuteSql(updateSql, list);
					}
					jsobject.put("respCode", "0");
					jsobject.put("respmsg", "权限保存成功！");
					jsobject.put("privJson", getPrivJson(jsdata));
					
				}else{
					jsobject.put("respCode", "1");
					jsobject.put("respmsg", "权限保存失败，请重试!");
				}
			}			
			
		} catch (Exception e) {
			e.printStackTrace();
			jsobject.put("respCode", "9");
			jsobject.put("respmsg", "系统忙，请联系系统管理员!");
		}
				
		
		return jsobject;
	}
	

	
	/**
	 * 
	 * @description：保存时根据业务功能组获取显示顺序
	 * @author LIU CHANG
	 * 
	 * @param groupOrder
	 * @return
	 * 
	 * @createDate 2018-03-16
	 * @createTime 下午4:46:23
	 */
	private int getSaveGroupOrder(String groupOrder)
	{
		try
		{
			String sql = "select max(display_Order) disorder from privilege where group_order='"
					+ groupOrder+"'";
			int i = baseDAO.findBySqlToJosn(sql).getJSONArray("list").getJSONObject(0).getInteger("disorder");
			
			return i;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return -1;
		}
	}
	
	
	
	
	/**
	 * 
	 * @description： 删除权限
	 * @author LIU CHANG
	 * 
	 * @param privilege
	 * @return
	 * 
	 * @createDate 2018-3-16
	 * @createTime 下午4:57:52
	 */
	public JSONObject delete(JSONObject jsdata){
		JSONObject jsobject = new JSONObject();
		try{
			String privCode = jsdata.getString("privCode");
			int rpIdCnt = getRolePrivCnt(privCode);
			int mPidCnt = getMenuCnt(privCode);
			
			if (rpIdCnt == 0 && mPidCnt == 0)
			{
				String sql= "delete from privilege where priv_code=?";
				ArrayList<JavaModel> list = new ArrayList<>();
				list.add(new JavaModel(privCode));
				baseDAO.excuteSql(sql, list);
				jsobject.put("respCode", "0");
				jsobject.put("respmsg", "权限删除成功！");
			}
			else
			{
				jsobject.put("respCode", "1");
				jsobject.put("respmsg", "检测到权限已在角色或菜单中分配，请先在相应功能中删除!");
			}
		}
		catch(Exception e){
			jsobject.put("respCode", "9");
			jsobject.put("respmsg", "系统忙，请联系系统管理员!");
		}
		return jsobject;
	}
	
	
	
	
	/**
	 * 
	 * @description：根据privCoid返回RolePriv表中已分配的privCode
	 * @author LIU CHANG
	 * 
	 * @param pId
	 * @return
	 * 
	 * @createDate 2014-6-19
	 * @createTime 上午9:02:43
	 */
	public int getRolePrivCnt(String privCode)
	{
		try
		{
			String sql ="SELECT count(*) FROM role_priv where priv_code='"+privCode+"'";
			
			int count = baseDAO.findBySqlCnt(sql);
			
			return count;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return -1;
		}
	}
	
	
	
	/**
	 * 
	 * @description：根据privCoid返回Menu表中已分配的privCode
	 * @author LIU CHANG
	 * 
	 * @param privCode
	 * @return
	 * 
	 * @createDate 2014-6-19
	 * @createTime 上午9:06:30
	 */
	public int getMenuCnt(String privCode)
	{
		try
		{
			String sql = "SELECT count(*) from Menu where menu_rights = '"
					+ privCode + "'";
			
     		int count = baseDAO.findBySqlCnt(sql);
			
			return count;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return -1;
		}
	}
	
}
